package com.godot.entity.manager;

import javax.jdo.PersistenceManager;
import javax.jdo.Transaction;

import com.godot.entity.checher.GodotChecher;
import com.godot.entity.factory.GodotFactory;
import com.godot.entity.persistent.Godot;
import com.google.appengine.api.datastore.KeyFactory;

public class GodotManger extends GodotChecher {

	public GodotManger(PersistenceManager pm) {
		super(pm);
	}
	
	public String register(String name, String pwd, String email) {
		Godot godot = this.getGodotByName(name);
		if (checkGodotShouldNotExists(godot) && checkGodotNameAvailable(name)) {
			godot = GodotFactory.createNewGodot(name, pwd);
			
			Transaction tx = _pm.currentTransaction();
			try {
				tx.begin();
				godot.setEmail(email);
				_pm.makePersistent(godot);
				tx.commit();
			} finally {
				if (tx.isActive()) {
					tx.rollback();
				}
			}
		}
		return KeyFactory.keyToString(godot.getKey());
	}
	
	public String login(String name, String pwd) {
		Godot godot = this.getGodotByName(name);
		String key = null;
		if (checkGodotShouldLogin(godot, pwd)) {
			godot.login();
			key = KeyFactory.keyToString(godot.getKey());
		}
		return key;
	}

}
